# -*- coding: utf-8 -*-
"""
@version: 1.0
@author: Pyma
@file: views
@time: 2019/10/9 21:36
"""
# 登录 登出 authenticate 验证以后授权
from io import BytesIO

from django.contrib.auth import login, logout, authenticate
from django.views.decorators.http import require_POST
from .forms import LoginForm, RegisterForm
# 定义json接口
from django.http import JsonResponse, HttpResponse
from utils import restful
from django.core.cache import cache

from django.shortcuts import redirect, reverse
from utils.captcha.xfzcaptcha import Captcha

from utils.aliyunsdk import aliyunsms
# User 模型
from django.contrib.auth import get_user_model
User = get_user_model()


# 与前端 json交互 一般这样设计
# {"code":400, "message":"","data":{}}

# 只允许ajax交互 json 方式 @require_POST
@require_POST
def login_view(request):
    form = LoginForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get("telephone")
        password = form.cleaned_data.get("password")
        remember = form.cleaned_data.get("remember")
        # 授权通过
        user = authenticate(request, username=telephone, password=password)
        if user:
            # 进行判断用户是否被拉黑
            if user.is_active:
                # 登录成功
                login(request, user)
                # 设置session
                if remember:
                    # 设置session默认两周
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                # return JsonResponse({"code":200, "message":"","data":{}})
                return restful.ok()
            else:
                # return JsonResponse({"code":405, "message":"你的账号已经被冻结了","data":{}})
                return restful.unauth(message="你的账号已经被冻结了")
        else:
            # return JsonResponse({"code":400, "message":"你的手机号码或者密码错误","data":{}})
            return restful.params_error(message="手机号或者密码错误！")
    else:
        errors = form.get_errors()
        # {"password":['密码最大长度不能超过20为！','xxx'],"telephone":['xx','x']}
        # return JsonResponse({"code":400, "message":"","data":errors})
        return restful.params_error(message=errors)


def logout_view(request):
    logout(request)
    return redirect(reverse("index"))

@require_POST
def register(request):
    form = RegisterForm(request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get("telephone")
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password1")
        user = User.objects.create_user(telephone=telephone, username=username, password=password)
        login(request, user)
        return restful.ok()
    else:
        print(form.get_errors())
        return restful.params_error(message=form.get_errors())



def img_captcha(request):
    text, image = Captcha.gene_code()
    # BytesIO 相当于一个管道 用来储存图片的流数据
    out = BytesIO()
    # 调用image的save方法 将这个image对象保存到BytesIO中
    image.save(out, "png")
    # 将BytesIO 的文件指针移到最开始的位置
    out.seek(0)

    response = HttpResponse(content_type="image/png")
    # 从BytesIO 的管道中，读出图片数据，保存到response对象中
    response.write(out.read())
    # 文件大小
    response["Content-length"] = out.tell()
    # key value 过期时间
    cache.set(text.lower(), text.lower(), 5*60)

    return response


def sms_captcha(request):
    # res = aliyunsms.send_sms("15102280550", "1234")
    # print(res)
    # return HttpResponse("SUCCES")
    # 电话号码
    telephone = request.GET.get("telephone")
    # 随机验证码
    code = Captcha.gene_text()
    cache.set(telephone, code, 5*60)
    print("短信验证码", code)
    # 短信验证提交
    result = aliyunsms.send_sms(telephone, code)
    return restful.ok()

# 测试缓存
# def cache_test(request):
#     cache.set("username", "zhiliao", 60)
#     result = cache.get("username")
#     print(result)
#     return HttpResponse("SUCCESS")

def cache_test(request):
    cache.set('username','###################################################',60)
    result = cache.get('username')
    print(result)
    return HttpResponse('success')






